﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using PlanningGIS.Util.IO;
using PlanningGIS.Util;
using PlanningGIS.Util.Configurations;
using System.Configuration;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Log;
using PlanningGIS.ArcGIS;

namespace PlanningGIS.Framework
{
    /// <summary>
    /// 应用程序实体对象
    /// </summary>
    public class ApplicationClass : IApplication, IApplicationEvents, IFramework
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public ApplicationClass()
        {
            MxDocument = new MxDocumentClass();
            StatusBar = new StatusBarClass();
            DockManager = new DockManagerClass();
            BarManager = new BarManagerClass();
        }

        #region EventHandler
        /// <summary>
        /// 当前按钮改变事件
        /// </summary>
        public event OnCurrentToolChangedEventHandler OnCurrentToolChangedEvent;

        /// <summary>
        /// 主窗体地图、布局、三维容器页选择改变事件
        /// </summary>
        public event OnMapPageSwitchEventHandler OnMapPageSwitchEvent;

        /// <summary>
        /// 打开地图文档事件
        /// </summary>
        public event IApplicationEvents_OpenDocumentEventHandler OpenedDocumentEventHandler;

        /// <summary>
        /// 地图改变事件
        /// </summary>
        public event MapChangedEventHandler MapChanged;
        #endregion

        #region 变量与属性
        /// <summary>
        /// 获取系统名称
        /// </summary>
        public string Name
        {
            get
            {
                return "基础平台系统";
            }
        }

        /// <summary>
        /// 获取或设置系统标题
        /// </summary>
        public string Caption { get; set; }

        /// <summary>
        /// 获取或设置图层树控件
        /// </summary>
        public ITOCControl2 TOCControl { get; set; }

        /// <summary>
        /// 获取或设置工具按钮控件
        /// </summary>
        public IToolbarControl ToolbarControl { get; set; }

        /// <summary>
        /// 三维控件
        /// </summary>
        private ISceneControl _SceneControl = null;

        /// <summary>
        /// 布局控件
        /// </summary>
        public IPageLayoutControl2 PageLayoutControl { get; private set; }

        /// <summary>
        /// 布局
        /// </summary>
        public IPageLayout PageLayout
        {
            get
            {
                return this.PageLayoutControl.PageLayout;
            }
        }

        /// <summary>
        /// 地图控件
        /// </summary>
        public IMapControl3 MapControl { get; private set; }

        /// <summary>
        /// 当前是否为地图控件
        /// </summary>
        public bool IsMapCtrlactive { get; private set; }

        /// <summary>
        /// 当前是否为布局控件
        /// </summary>
        public bool IsPageLayoutActive { get; private set; }

        /// <summary>
        /// 当前是否为布局控件
        /// </summary>
        public bool IsSceneCtlActive { get; private set; }
        
        /// <summary>
        /// 获取或设置捕捉距离
        /// </summary>
        public double SnapTolerance { get; set; }

        /// <summary>
        /// 获取或设置容差范围
        /// </summary>
        public double Tolerance { get; set; }

        /// <summary>
        /// 获取或设置工具条管理对象
        /// </summary>
        public IBarManager BarManager { get; set; }

        /// <summary>
        /// 获取或设置菜单可停靠控件管理对象
        /// </summary>
        public IDockManager DockManager { get; set; }

        /// <summary>
        /// 当前的工具按钮
        /// </summary>
        private ICommandItem _CurrentTool;

        /// <summary>
        /// 获取或设置当前的工具按钮
        /// </summary>
        public ICommandItem CurrentTool
        {
            get
            {
                return _CurrentTool;
            }
            set
            {
                _CurrentTool = value;
                if (IsMapCtrlactive)
                {
                    if (this.MapControl != null && _CurrentTool != null)
                    {
                        this.MapControl.CurrentTool = _CurrentTool.Command as ITool;
                    }
                }
                else if (IsPageLayoutActive)
                {
                    if (this.PageLayoutControl != null && _CurrentTool != null)
                    {
                        this.PageLayoutControl.CurrentTool = _CurrentTool.Command as ITool;
                    }
                }
                else
                {
                    if (this._SceneControl != null && _CurrentTool != null)
                    {
                        this._SceneControl.CurrentTool = _CurrentTool.Command as ITool;
                    }
                }
                if (this.OnCurrentToolChangedEvent != null)
                {
                    this.OnCurrentToolChangedEvent(_CurrentTool.Command as ITool);
                }
            }
        }
        
        /// <summary>
        /// 获取或设置当前的工具按钮
        /// </summary>
        public ITool Tool
        {
            get
            {
                if (IsMapCtrlactive)
                {
                    if (this.MapControl != null)
                        return this.MapControl.CurrentTool;
                    else
                        return null;
                }
                else if (IsPageLayoutActive)
                {
                    if (this.PageLayoutControl != null)
                        return this.PageLayoutControl.CurrentTool;
                    else
                        return null;
                }
                else
                {
                    if (this._SceneControl != null)
                        return this._SceneControl.CurrentTool;
                    else
                        return null;
                }
            }
            set
            {
                if (IsMapCtrlactive)
                {
                    if (this.MapControl != null)
                    {
                        this.MapControl.CurrentTool = value;
                    }
                }
                else if (IsPageLayoutActive)
                {
                    if (this.PageLayoutControl != null)
                    {
                        this.PageLayoutControl.CurrentTool = value;
                    }
                }
                else
                {
                    if (this._SceneControl != null)
                    {
                        this._SceneControl.CurrentTool = value;
                    }
                }
                if (this.OnCurrentToolChangedEvent != null)
                {
                    this.OnCurrentToolChangedEvent(value);
                }
            }
        }

        /// <summary>
        /// 获取或设置当前绑定的地图对象，在ArcGIS自带的OnCreate中可以传递该参数
        /// </summary>
        public object Object
        {
            get
            {
                if (IsMapCtrlactive)
                    return MapControl.Object;
                else if (IsPageLayoutActive)
                    return PageLayoutControl.Object;
                else
                    return _SceneControl.Object;
            }
            set
            {
                if (value == null)
                {
                    this.MapControl = null;
                    this.PageLayoutControl = null;
                    this._SceneControl = null;
                }
                else if (value is IMapControl3)
                {
                    this.MapControl = (IMapControl3)value;
                }
                else if (value is IPageLayoutControl2)
                {
                    this.PageLayoutControl = (IPageLayoutControl2)value;
                }
                else if (value is ISceneControl)
                {
                    this._SceneControl = (ISceneControl)value;
                }
            }
        }

        /// <summary>
        /// 获取或设置主窗体控件
        /// </summary>
        public Form MdiForm { get; set; }

        /// <summary>
        /// 获取状态栏对象
        /// </summary>
        public IStatusBar StatusBar { get; private set; }

        /// <summary>
        /// 地图文档对象
        /// </summary>
        public IMxDocument MxDocument { get; set; }
        
        /// <summary>
        /// 获取地图文档对象
        /// </summary>
        public IDocument Document
        {
            get
            {
                try
                {
                    MxDocument.ActiveView = this.MapControl.ActiveView;
                    MxDocument.PageLayout = this.PageLayout;
                    return MxDocument as IDocument;
                }
                catch
                {
                    return null;
                }
            }
        }
        
        /// <summary>
        /// 获取当前活动的视图
        /// </summary>
        public IActiveView ActiveView
        {
            get
            {
                return this.FocusMap as IActiveView;
            }
        }
        
        /// <summary>
        /// 获取当前的地图
        /// </summary>
        public IMap FocusMap
        {
            get
            {
                if (this.MapControl != null)
                {
                    return this.MapControl.Map;
                }
                if (this.PageLayoutControl != null)
                {
                    return this.PageLayoutControl.ActiveView.FocusMap;
                }
                return null;
            }
        }
        
        /// <summary>
        /// 获取当前的操作堆栈
        /// </summary>
        public IOperationStack OperationStack
        {
            get
            {
                return this.MxDocument.OperationStack;
            }
        }

        #endregion

        /// <summary>
        /// 绑定系统基础控件
        /// </summary>
        /// <param name="mapControl">地图控件</param>
        /// <param name="pageLayoutControl">布局控件</param>
        /// <param name="sceneControl">三维控件</param>
        /// <param name="activateMapFirst">是否开始激活地图控件</param>
        public void BindControls(IMapControl3 mapControl, IPageLayoutControl2 pageLayoutControl, ISceneControl sceneControl, bool activateMapFirst)
        {
            if (mapControl == null || pageLayoutControl == null)
                throw new Exception("地图控件或布局控件没有初始化!");
            this.MapControl = mapControl;
            this.PageLayoutControl = pageLayoutControl;
            this._SceneControl = sceneControl;
            IMap newMap = new MapClass();
            newMap.Name = "Map";
            IMaps maps = new Maps();
            maps.Add(newMap);
            PageLayoutControl.PageLayout.ReplaceMaps(maps);
            MapControl.Map = newMap;
            if (activateMapFirst)
                ActivateMapControl();
            else
                ActivatePageLayoutControl();
        }

        /// <summary>
        /// 激活地图控件
        /// </summary>
        public void ActivateMapControl()
        {
            if (this.PageLayoutControl != null)
            {
                PageLayoutControl.ActiveView.Deactivate();
            }
            MapControl.ActiveView.Activate(MapControl.hWnd);
            (MapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, (MapControl.Map as IActiveView).Extent);
            IsMapCtrlactive = true;
            IsPageLayoutActive = false;
            IsSceneCtlActive = false;
            SetBuddies(this.MapControl.Object);
        }

        /// <summary>
        /// 激活布局控件
        /// </summary>
        public void ActivatePageLayoutControl()
        {
            IMaps maps = new Maps();
            maps.Add(this.MapControl.Map);
            MapControl.ActiveView.Deactivate();
            this.PageLayoutControl.PageLayout.ReplaceMaps(maps);
            PageLayoutControl.ActiveView.Activate(PageLayoutControl.hWnd);
            IsMapCtrlactive = false;
            IsPageLayoutActive = true;
            IsSceneCtlActive = false;
            SetBuddies(this.PageLayoutControl.Object);
        }
        
        /// <summary>
        /// 激活三维控件
        /// </summary>
        public void ActivateSceneControl()
        {
            IsMapCtrlactive = false;
            IsPageLayoutActive = false;
            IsSceneCtlActive = true;
            SetBuddies(this._SceneControl.Object);
        }

        /// <summary>
        /// 绑定图层树
        /// </summary>
        /// <param name="buddy">要绑定的对象</param>
        private void SetBuddies(object buddy)
        {
            try
            {
                if (buddy == null)
                    throw new Exception("SetBuddies:要绑定到图层树的对象为空!");
                if (TOCControl != null)
                {
                    TOCControl.SetBuddyControl(buddy);
                }
                if (ToolbarControl != null)
                {
                    ToolbarControl.SetBuddyControl(buddy);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SetBuddies:\r\n{0}", ex.Message));
            }
        }

        /// <summary>
        /// 执行按钮命令操作
        /// </summary>
        /// <param name="command"></param>
        public void ExecuteCommand(ICommand command)
        {
            try
            {
                command.OnClick();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }

        /// <summary>
        /// 处理主窗体地图、布局、三维容器页选择改变后的相关操作
        /// </summary>
        public void RaiseMapPageSwitchEvent()
        {
            if (OnMapPageSwitchEvent != null)
                OnMapPageSwitchEvent();
        }

        /// <summary>
        /// 获取当前屏幕坐标
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public System.Drawing.Point LocationPoint(int x, int y)
        {
            int inthWnd = 0;
            if (IsMapCtrlactive)
                inthWnd = MapControl.hWnd;
            else
                inthWnd = PageLayoutControl.hWnd;
            System.IntPtr ptr = (System.IntPtr)inthWnd;
            Control c = Control.FromHandle(ptr);
            return c.PointToScreen(new System.Drawing.Point(x, y));
        }

        /// <summary>
        /// 获取停靠控件中的数据控件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object GetControlUserData(string name)
        {
            Control m_Control = this.DockManager.GetControlFromDockPanel(name);
            return FindDockableWindowData(m_Control);
        }

        /// <summary>
        /// 查找停靠控件
        /// </summary>
        /// <param name="m_Control"></param>
        /// <returns></returns>
        private object FindDockableWindowData(Control m_Control)
        {
            if (m_Control == null) return null;
            if (m_Control is IDockableWindow)
                return (m_Control as IDockableWindow).UserData;
            else
            {
                foreach (Control c1 in m_Control.Controls)
                {
                    return FindDockableWindowData(c1);
                }
            }
            return null;
        }

        /// <summary>
        /// 退出系统
        /// </summary>
        public void Shutdown()
        {
            (MxDocument as IDocument).Close();
        }

        #region Document

        /// <summary>
        /// 改变当前地图
        /// </summary>
        /// <param name="name">地图名称，名称需要在当前模板中存在</param>
        public void ChangeMap(string name)
        {
            if (Document == null)
            {
                MsgHelper.ShowInfomationAlert("请先加载地图文档！");
                return;
            }
            if (Document.Maps == null || Document.Maps.Count == 0)
            {
                MsgHelper.ShowInfomationAlert("地图文档中不存在地图！");
                return;
            }
            IMap m = Document.Maps.FirstOrDefault(t => t.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
            if (m == null)
            {
                MsgHelper.ShowInfomationAlert("地图文档中不存在名称为【" + name + "】的地图！");
                return;
            }
            ReplaceMap(m);
            try
            {
                (Document as MxDocumentClass).MapDocument.SetActiveView(m as IActiveView);
            }
            catch 
            {
            }
            
        }

        /// <summary>
        /// 更新地图
        /// </summary>
        /// <param name="newMap"></param>
        public void ReplaceMap(IMap newMap)
        {
            if (newMap == null) throw new Exception("要替换的地图对象不能为空!");
            if (this.PageLayoutControl == null || this.MapControl == null) throw new Exception("地图或布局控件不能为空");
            IMaps maps = new Maps();
            maps.Add(newMap);
            bool bIsMapActive = IsMapCtrlactive;
            this.ActivatePageLayoutControl();
            this.PageLayoutControl.PageLayout.ReplaceMaps(maps);
            MapControl.Map = newMap;
            MapChanged?.Invoke(newMap);
            if (bIsMapActive)
            {
                this.ActivateMapControl();
                //(MapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, (MapControl.Map as IActiveView).Extent);
            }
            else
            {
                this.ActivatePageLayoutControl();
                PageLayoutControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, PageLayoutControl.ActiveView.Extent);
            }
        }

        /// <summary>
        /// 保存工作区
        /// </summary>
        /// <param name="saveAsPath"></param>
        public void SaveDocument(string saveAsPath)
        {
            (MxDocument as IDocument).SaveDocument(saveAsPath);
        }

        /// <summary>
        /// 另存工作区
        /// </summary>
        /// <param name="saveAsPath"></param>
        public void SaveAsDocument(string saveAsPath)
        {
            (MxDocument as IDocument).SaveAsDocument(saveAsPath);
            OpenDocument(saveAsPath);
        }

        /// <summary>
        /// 打开工作区
        /// </summary>
        /// <param name="path">工作区路径</param>
        public void OpenDocument(string path)
        {
            try
            {
                if (!IsSceneCtlActive) FrameworkHelper.SaveEdit();
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                if (IsMapCtrlactive || IsPageLayoutActive)
                {
                    string strExt = System.IO.Path.GetExtension(path).ToLower();
                    if (strExt.Equals(".mxd") || strExt.Equals(".mxt") || strExt.Equals(".pmf"))
                    {
                        if (MapControl != null && MapControl.CheckMxFile(path))
                        {
                            (MxDocument as IDocument).Open(path, "");
                            IMap map = (MxDocument as IDocument).ActivedView.FocusMap;
                            ReplaceMap(map);
                            string file = System.IO.Path.GetFileName(path);
                            string caption = (this as IFramework).MdiForm.Text;
                            if (caption.IndexOf("[") > 0)
                            {
                                caption = caption.Substring(0, caption.IndexOf("[")) + "[" + file + "]";
                            }
                            else
                            {
                                caption = caption + "[" + file + "]";
                            }
                            (this as IFramework).MdiForm.Text = caption;
                            OpenedDocumentEventHandler?.Invoke();
                        }
                        else
                        {
                            NewDocument(false, "");
                        }
                        MxDocument.ActiveView = this.ActiveView;
                        MxDocument.PageLayout = this.PageLayout;

                        //ESRI.ArcGIS.Carto.IActiveViewEvents_Event actviewEvents = MxDocument.ActiveView as ESRI.ArcGIS.Carto.IActiveViewEvents_Event;
                        //actviewEvents.ContentsChanged -= new ESRI.ArcGIS.Carto.IActiveViewEvents_ContentsChangedEventHandler(actviewEvents_ContentsChanged);
                        //actviewEvents.ContentsChanged += new ESRI.ArcGIS.Carto.IActiveViewEvents_ContentsChangedEventHandler(actviewEvents_ContentsChanged);
                    }
                    MxDocument.ActiveView.ScreenDisplay.UpdateWindow();
                }
                else if (IsSceneCtlActive)
                {
                    _SceneControl.LoadSxFile(path);
                }
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 新建工作区
        /// </summary>
        /// <param name="selectTemplate"></param>
        /// <param name="templatePath"></param>
        public void NewDocument(bool selectTemplate, string templatePath)
        {
            try
            {
                if (!IsSceneCtlActive) FrameworkHelper.SaveEdit();
                this.MapControl.Map.ClearLayers();
                this.MapControl.Map.SpatialReference = null;
                if ((MxDocument as MxDocumentClass).MapDocument != null)
                    (MxDocument as MxDocumentClass).MapDocument.Close();

                (MxDocument as MxDocumentClass).New("无标题.mxd");

                string caption = (this as IFramework).MdiForm.Text;
                if (caption.IndexOf("[") > 0)
                {
                    caption = caption.Substring(0, caption.IndexOf("[")) + "[无标题.mxd]";
                }
                else
                {
                    caption = caption + "[无标题.mxd]";
                }
                (this as IFramework).MdiForm.Text = caption;

                IMap map = (MxDocument as IDocument).get_Map(0);
                map.Name = "Layers";
                ReplaceMap(map);

                MxDocument.ActiveView = this.ActiveView;
                MxDocument.PageLayout = this.PageLayout;

                //ESRI.ArcGIS.Carto.IActiveViewEvents_Event actviewEvents = MxDocument.ActiveView as ESRI.ArcGIS.Carto.IActiveViewEvents_Event;
                //actviewEvents.ContentsChanged -= new ESRI.ArcGIS.Carto.IActiveViewEvents_ContentsChangedEventHandler(actviewEvents_ContentsChanged);
                //actviewEvents.ContentsChanged += new ESRI.ArcGIS.Carto.IActiveViewEvents_ContentsChangedEventHandler(actviewEvents_ContentsChanged);

                //if (selectTemplate)
                //{
                //    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                //    if (templatePath.EndsWith(".mxt"))
                //    {
                //        if (m_MapControl != null && m_MapControl.CheckMxFile(templatePath))
                //        {
                //            (m_Document as IDocument).Open(templatePath, "");
                //            IMap map = (m_Document as IDocument).get_Map(0);
                //            ReplaceMap(map);
                //        }
                //    }
                //    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                //}
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }
        
        #endregion
          
        #region 资源树右键菜单
        /// <summary>
        /// 
        /// </summary>
        /// <param name="datasetsall"></param>
        public void RemoveLayersFromMapControl(List<IDataset> datasetsall)
        {
            if (this.MapControl == null) return;
            foreach (IDataset dataset in datasetsall)
            {
                if (dataset.Type == esriDatasetType.esriDTFeatureDataset)
                {
                    IEnumDataset datasets = dataset.Subsets;
                    IDataset t_Dataset = datasets.Next();
                    while (t_Dataset != null)
                    {
                        IFeatureClass fClass = t_Dataset as IFeatureClass;
                        foreach (IFeatureLayer layer in FindLayersByDs(this.MapControl.Map, (IDataset)fClass))
                        {
                            this.MapControl.Map.DeleteLayer(layer);
                        }
                        t_Dataset = datasets.Next();
                    }
                }
                else
                {
                    //ym 20091203 update
                    List<ILayer> m_Layers = FindLayersByDs(this.MapControl.Map, dataset);
                    foreach (ILayer layer in m_Layers)
                    {
                        this.MapControl.Map.DeleteLayer(layer);
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="datasetsall"></param>
        public void VisibleLayersFromMapControl(List<IDataset> datasetsall)
        {
            if (this.MapControl == null)
                return;
            foreach (IDataset dataset in datasetsall)
            {
                if (dataset.Type == esriDatasetType.esriDTFeatureDataset)
                {
                    IEnumDataset datasets = dataset.Subsets;
                    IDataset t_Dataset = datasets.Next();
                    while (t_Dataset != null)
                    {
                        IFeatureClass fClass = t_Dataset as IFeatureClass;
                        foreach (IFeatureLayer layer in FindLayersByDs(this.MapControl.Map, (IDataset)fClass))
                        {
                            layer.Visible = true;
                        }
                        t_Dataset = datasets.Next();
                    }
                }
                else
                {
                    //ym 20091203 update
                    List<ILayer> m_Layers = FindLayersByDs(this.MapControl.Map, dataset);
                    foreach (ILayer layer in m_Layers)
                    {
                        layer.Visible = true;
                    }
                }
            }
            //this.m_MapControl.ActiveView.Refresh();
            this.MapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, this.MapControl.ActiveView.Extent);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="datasetsall"></param>
        public void UnVisibleLayersFromMapControl(List<IDataset> datasetsall)
        {
            if (this.MapControl == null) return;
            foreach (IDataset dataset in datasetsall)
            {
                if (dataset.Type == esriDatasetType.esriDTFeatureDataset)
                {
                    IEnumDataset datasets = dataset.Subsets;
                    IDataset t_Dataset = datasets.Next();
                    while (t_Dataset != null)
                    {
                        IFeatureClass fClass = t_Dataset as IFeatureClass;
                        foreach (IFeatureLayer layer in FindLayersByDs(this.MapControl.Map, (IDataset)fClass))
                        {
                            layer.Visible = false;
                        }
                        t_Dataset = datasets.Next();
                    }
                }
                else
                {
                    //ym 20091203 update
                    List<ILayer> m_Layers = FindLayersByDs(this.MapControl.Map, dataset);
                    foreach (ILayer layer in m_Layers)
                    {
                        layer.Visible = false;
                    }
                }
            }
            //this.m_MapControl.ActiveView.Refresh();
            this.MapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography | esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, this.MapControl.ActiveView.Extent);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pMap"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static List<ILayer> FindLayersByDs(IMap pMap, IDataset ds)
        {
            List<ILayer> pLayers = new List<ILayer>();
            List<ILayer> lys = MapHelper.GetAllLayer(pMap);
            foreach (ILayer lyr in lys)
            {
                IDataset pTempDs = null;
                if (lyr is IFeatureLayer)
                {
                    pTempDs = ((IFeatureLayer)lyr).FeatureClass as IDataset;
                    if (ds.Workspace.Equals(pTempDs.Workspace))
                    {
                        //sdc后缀的要素类文件objectclassid总为-1
                        if (((IFeatureClass)pTempDs).ObjectClassID == -1 || ((IFeatureClass)ds).ObjectClassID == -1)
                        {
                            if (ds.Name == pTempDs.Name)
                            {
                                pLayers.Add(lyr);
                            }
                        }
                        else
                        {
                            if (((IFeatureClass)pTempDs).ObjectClassID == ((IFeatureClass)ds).ObjectClassID)
                            {
                                pLayers.Add(lyr);
                            }
                        }
                    }
                }
                else if (lyr is IRasterLayer)
                {
                    if (lyr.Name == ds.Name)
                    {
                        pLayers.Add(lyr);
                    }
                }
                else if (lyr is IGdbRasterCatalogLayer)
                {
                    if (lyr.Name == ds.Name)
                    {
                        pLayers.Add(lyr);
                    }
                }
            }
            return pLayers;
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="layers"></param>
        public void AddLayersToMapControl(ILayer[] layers)
        {

            List<ILayer> annoLayers = null;
            List<ILayer> pointLayers = null;
            List<ILayer> polylineLayers = null;
            List<ILayer> otherLayers = null;
            List<ILayer> polygonLayers = null;

            #region 按照点线面分别排序
            foreach (ILayer layer in layers)
            {
                if (layer is IFDOGraphicsLayer)
                {
                    if (annoLayers == null)
                        annoLayers = new List<ILayer>();
                    annoLayers.Add(layer);
                }
                else if (layer is IFeatureLayer)
                {
                    IFeatureLayer fLayer = layer as IFeatureLayer;
                    if (fLayer.FeatureClass != null)
                    {
                        #region esriGeometryType
                        switch (fLayer.FeatureClass.ShapeType)
                        {
                            case esriGeometryType.esriGeometryPoint:
                                if (pointLayers == null)
                                {
                                    pointLayers = new List<ILayer>();
                                }
                                pointLayers.Add(layer);
                                break;
                            case esriGeometryType.esriGeometryPolyline:
                                if (polylineLayers == null)
                                {
                                    polylineLayers = new List<ILayer>();
                                }
                                polylineLayers.Add(layer);
                                break;
                            case esriGeometryType.esriGeometryPolygon:
                                if (polygonLayers == null)
                                {
                                    polygonLayers = new List<ILayer>();
                                }
                                polygonLayers.Add(layer);
                                break;
                            default:
                                if (pointLayers == null)
                                {
                                    pointLayers = new List<ILayer>();
                                }
                                pointLayers.Add(layer);
                                break;
                        }
                        #endregion
                    }
                    else
                    {
                        if (otherLayers == null)
                        {
                            otherLayers = new List<ILayer>();
                        }
                        otherLayers.Add(layer);
                    }
                }
                else
                {
                    if (otherLayers == null)
                    {
                        otherLayers = new List<ILayer>();
                    }
                    otherLayers.Add(layer);
                }
            }
            #endregion

            List<ILayer> allLayers = new List<ILayer>();
            if (polygonLayers != null)
                allLayers.AddRange(polygonLayers);
            if (otherLayers != null)
                allLayers.AddRange(otherLayers);
            if (polylineLayers != null)
                allLayers.AddRange(polylineLayers);
            if (pointLayers != null)
                allLayers.AddRange(pointLayers);
            if (annoLayers != null)
                allLayers.AddRange(annoLayers);

            //按照点线面的顺序加入到地图上                                           

            foreach (ILayer layer in allLayers)
            {
                if (this.MapControl != null)
                {
                    if (layer is IGeoDataset)
                    {
                        IGeoDataset geodataset = layer as IGeoDataset;
                        if (geodataset.SpatialReference != null && (this.MapControl.SpatialReference == null || this.MapControl.SpatialReference.Name.ToLower() == "unknown"))
                        {
                            this.MapControl.SpatialReference = geodataset.SpatialReference;
                        }
                    }
                }
                if (this.MapControl != null)
                    this.MapControl.AddLayer(layer, 0);
            }
            if (this.TOCControl != null)
                this.TOCControl.Update();
        }
        #endregion
    }
}
